package com.wedimob.slideshare.task.network;

import java.net.URL;

import org.jsoup.nodes.Document;

import com.wedimob.slideshare.RuntimeConfig;
import com.wedimob.slideshare.WriteType;
import com.wedimob.slideshare.bo.Summary;
import com.wedimob.slideshare.task.PoolExecutor;
import com.wedimob.slideshare.task.Task;
import com.wedimob.slideshare.task.TaskType;
import com.wedimob.slideshare.task.WhatToDoAfter;
import com.wedimob.slideshare.task.cpu.TaskAuthorsExtractor;
import com.wedimob.slideshare.task.cpu.TaskDocumentExtractor;
import com.wedimob.slideshare.task.cpu.TaskSummariesExtractor;

public class TaskHtmlDownloader extends Task<URL, Document> {

    private WhatToDoAfter after;
    private boolean recursiveMode;
    private Summary summary;
    private WriteType write;

    public TaskHtmlDownloader(PoolExecutor pool, URL url, WhatToDoAfter after,
            boolean recursiveMode, WriteType write, int limit, int timeout) {
        super(TaskType.NETWORK, pool, url, limit, timeout);
        this.after = after;
        this.recursiveMode = recursiveMode;
        this.write = write;
    }

    public TaskHtmlDownloader(PoolExecutor pool, Summary summary, WriteType write, int timeout) {
        super(TaskType.NETWORK, pool, summary.getUrl(), 0, timeout);
        this.summary = summary;
        this.after = WhatToDoAfter.EXTRACT_DOCUMENT;
        this.recursiveMode = false;
        this.write = write;
    }

    @Override
    public void run() {
        try {
            output = RuntimeConfig.getInstance().getReader().get(input, timeout);

            switch (after) {
            case NONE:
                pool.getResults().putResult(output);
                break;
            case EXTRACT_AUTHOR:
                pool.execAsync(new TaskAuthorsExtractor(pool, output, write, limit, timeout));
                break;
            case EXTRACT_SUMMARY:
                pool.execAsync(new TaskSummariesExtractor(pool,
                        output, recursiveMode, write, limit, timeout));
                break;
            case EXTRACT_DOCUMENT:
                pool.execAsync(new TaskDocumentExtractor(pool, summary,
                        output, write, timeout));
            }

        } catch (Exception e) {
            e.printStackTrace();
            this.e = e;
        }
    }
}
